package com.yimils.core.sys.dto;


import com.yimils.core.sys.entity.DeptEntity;
import com.yimils.core.sys.vo.DeptVo;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class DeptDto {

    public DeptEntity reqToEntity(ReqAddDept vo) {
        DeptEntity entity = new DeptEntity();
        entity.setName(vo.getName());
        entity.setParentId(vo.getParentId());
        entity.setSort(vo.getSort());
        return entity;
    }

    public DeptVo EntityToVo(List<DeptEntity> list) {
        DeptVo vo = new DeptVo();
        vo.setDept(new ArrayList<>());
        List<DeptEntity> parents = list.stream().filter(item -> item.getParentId() == null).collect(Collectors.toList());
        parents.forEach(parent -> {
            DeptVo.Node node = makeNode(parent);
            List<DeptEntity> children = list.stream().
                    filter(item -> item.getParentId() != null && item.getParentId().equals(parent.getId()))
                    .collect(Collectors.toList());
            if (children.size() > 0) {
                node.setChildren(new ArrayList<>());
            }
            children.forEach(child -> {
                node.getChildren().add(makeNode(child));
            });
            vo.getDept().add(node);
        });
        //部门根据sort值自然排序
        List<DeptVo.Node> parentList = vo.getDept().stream().sorted(Comparator.comparing(DeptVo.Node::getSort)).collect(Collectors.toList());
        parentList.forEach(item -> {
            if (item.getChildren() != null) {
                List<DeptVo.Node> childrenList = item.getChildren().stream().sorted(Comparator.comparing(DeptVo.Node::getSort)).collect(Collectors.toList());
                item.setChildren(childrenList);
            }
        });
        vo.setDept(parentList);
        return vo;
    }

    public DeptVo.Node makeNode(DeptEntity entity) {
        DeptVo.Node node = new DeptVo.Node();
        node.setId(entity.getId());
        node.setName(entity.getName());
        node.setParentId(entity.getParentId());
        node.setSort(entity.getSort());
        return node;
    }
}
